<script setup>
import { ref, computed, watch, watchEffect } from 'vue'
import BaseRankingChart from '@/components/chart/BaseRankingChart.vue'
import BasePieChart from '@/components/chart/BasePieChart.vue'
import BaseChart from '@/components/chart/BaseChart.vue'
import CustomDatePicker from '@/components/header/CustomDatePicker.vue'
import { useCompanyStore } from '@/stores/company'
import dayjs from 'dayjs'
import { getAllSubCategoryReportApi, getSubCategoryReportApi } from '@/api/category'
import CustomDateRadio from '@/components/header/CustomDateRadio.vue'
import { handleError } from '@/utils/handleError'
import { generateTimeConfig } from '@/utils/date'
import { useMobileDetection } from '@/composables/useMobileDetection'
let companyStore = useCompanyStore()
const selectedSubCategory = ref(null)

// 加载状态
const pieChartLoading = ref(false)
const rankingChartLoading = ref(false)
const trendChartLoading = ref(false)
const tableLoading = ref(false)

// 饼图数据和时间控制
const pieChartTime = ref(null)
const PieChartData = ref([])

// 排名图数据和时间控制
const rankingChartTime = ref(null)
const RankingChartData = ref([])

// 趋势图数据和时间控制
const chartData = ref([])
const chartTimeRange = ref(null)

// 表格相关
const tableRef = ref(null)
const tableTimeConfig = generateTimeConfig('monthly', 0) || { start_time: 0, end_time: 0 }
let tableDataRange = ref([
    tableTimeConfig.start_time,  // 月初
    tableTimeConfig.end_time     // 月末或今天的时间(根据generateTimeConfig的逻辑)
])

const subcategoryData = ref([])

// 端类型检测统一
const { isMobile, isTablet, isPC } = useMobileDetection();
const rankingHorizontal = computed(() => isPC.value);

// 获取用途总数据的通用方法
async function getSubCategoryTotalData(start_time, end_time, interval = '') {
    if (!start_time || !end_time) return null

    // 检查公司ID
    if (!companyStore?.currentCompany?.id) {
        console.warn('当前公司ID不存在');
        return null;
    }

    try {
        let res = await getAllSubCategoryReportApi({
            id: companyStore.currentCompany.id,
            start_time,
            end_time,
            interval,
            type: 1,
        })

        // 检查返回的数据格式
        if (!res || !res.aggregated_data) {
            console.warn('获取用途数据返回格式不正确:', res);
            return null;
        }

        return res.aggregated_data
    } catch (error) {
        handleError(error, '获取用途数据失败')
        return null
    }
}

// 监听饼图时间变化
watchEffect(async () => {
    if (pieChartTime.value) {
        pieChartLoading.value = true
        try {
            let data = await getSubCategoryTotalData(pieChartTime.value.start_time, pieChartTime.value.end_time)
            if (data) {
                // 确保data是数组
                if (!Array.isArray(data)) {
                    console.warn('饼图数据格式不正确, 期望数组但收到:', typeof data);
                    PieChartData.value = [];
                    return;
                }

                PieChartData.value = data.flat()
                    .map(item => {
                        // 添加项目级别的空值检查
                        if (!item) return null;

                        // 确保usage是数组
                        const usage = Array.isArray(item.usage) ? item.usage : [];

                        return {
                            name: item.subcategory || '其他',
                            value: usage.reduce((acc, meter) => {
                                // 安全地获取并转换Used值
                                const used = meter && typeof meter.Used !== 'undefined' ? Number(meter.Used) : 0;
                                return acc + used;
                            }, 0),
                            subcategory: item.subcategory
                        };
                    })
                    .filter(item => item !== null && item.value > 0)
                    .sort((a, b) => b.value - a.value)
            } else {
                PieChartData.value = [];
            }
        } catch (error) {
            handleError(error, '获取饼图数据失败')
            PieChartData.value = [];
        } finally {
            pieChartLoading.value = false
        }
    }
})

// 监听排名图时间变化
watchEffect(async () => {
    if (rankingChartTime.value) {
        rankingChartLoading.value = true
        try {
            let data = await getSubCategoryTotalData(rankingChartTime.value.start_time, rankingChartTime.value.end_time)
            if (data) {
                // 确保data是数组
                if (!Array.isArray(data)) {
                    console.warn('排名图数据格式不正确, 期望数组但收到:', typeof data);
                    RankingChartData.value = [];
                    return;
                }

                RankingChartData.value = data.flat()
                    .map(item => {
                        // 添加项目级别的空值检查
                        if (!item) return null;

                        // 确保usage是数组
                        const usage = Array.isArray(item.usage) ? item.usage : [];

                        return {
                            name: item.subcategory || '其他',
                            value: usage.reduce((acc, meter) => {
                                // 安全地获取并转换Used值
                                const used = meter && typeof meter.Used !== 'undefined' ? Number(meter.Used) : 0;
                                return acc + used;
                            }, 0),
                            subcategory: item.subcategory
                        };
                    })
                    .filter(item => item !== null)
                    .sort((a, b) => b.value - a.value)

                selectedSubCategory.value = RankingChartData.value[0].subcategory
            } else {
                RankingChartData.value = [];
            }
        } catch (error) {
            handleError(error, '获取排名数据失败')
            RankingChartData.value = [];
        } finally {
            rankingChartLoading.value = false
        }
    }
})

async function getSubCategoryData() {
    if (!selectedSubCategory.value || !chartTimeRange.value) return

    // 检查公司ID
    if (!companyStore?.currentCompany?.id) {
        console.warn('当前公司ID不存在');
        return;
    }

    trendChartLoading.value = true
    try {
        let res = await getSubCategoryReportApi({
            id: companyStore.currentCompany.id,
            sub_category: selectedSubCategory.value,
            ...chartTimeRange.value,
            type: 1
        })

        // 添加空值检查
        if (!res?.aggregated_data) {
            console.warn('趋势图数据返回格式不正确:', res);
            chartData.value = []
            return
        }

        // 确保aggregated_data是数组
        const aggregatedData = Array.isArray(res.aggregated_data) ? res.aggregated_data : [];

        chartData.value = aggregatedData
            .filter((item) => Array.isArray(item) && item.length > 0)  // 确保item是数组且长度大于0
            .map(item => {
                let formatStr = 'YYYY-MM-DD'
                switch (chartTimeRange.value?.interval) {  // 添加可选链操作符
                    case 'day':
                        formatStr = 'MM-DD'
                        break
                    case 'month':
                        formatStr = 'YYYY-MM'
                        break
                    case 'year':
                        formatStr = 'YYYY'
                        break
                    case 'quarter':
                        formatStr = 'Q季度'
                        break
                }

                // 添加安全的数据获取
                const startTime = item[0]?.StartTime

                // 安全地计算总值
                const value = item.reduce((acc, cur) => {
                    // 确保cur.Used是有效数字
                    const used = cur && typeof cur.Used !== 'undefined' ? Number(cur.Used) : 0;
                    return acc + used;
                }, 0).toFixed(2)

                return {
                    time: startTime ? dayjs(startTime).format(formatStr) : '-',
                    timestamp: startTime ? dayjs(startTime).valueOf() : 0,
                    value: value
                }
            })
            .filter(item => {
                return item !== null && item.timestamp !== -62135596800000
            })
            .sort((a, b) => a.timestamp - b.timestamp)
    } catch (error) {
        handleError(error, '获取趋势图数据失败')
        chartData.value = []  // 发生错误时设置为空数组
    } finally {
        trendChartLoading.value = false
    }
}

// 监听趋势图数据变化
watchEffect(getSubCategoryData)

// 趋势图配置
const chartOptions = computed(() => ({
    xAxisData: chartData.value?.map(item => item.time) || [],
    yAxisUnit: 'm³',
    series: [
        {
            name: '用水量',
            type: 'line',
            data: chartData.value?.map(item => item.value) || [],
        }
    ],
    customColors: ['#409EFF', '#909399']
}))

// 监听表格数据变化
watchEffect(async () => {
    if (tableDataRange.value && tableDataRange.value[0] && tableDataRange.value[1]) {
        tableLoading.value = true
        try {
            let tempData = []
            let data = await getSubCategoryTotalData(tableDataRange.value[0], tableDataRange.value[1], 'day')
            if (data && Array.isArray(data) && data.length > 0) {
                // 处理第一天的数据
                if (Array.isArray(data[0])) {
                    data[0].forEach(item => {
                        if (!item) return;

                        // 确保usage是数组并且有元素
                        const usage = Array.isArray(item.usage) && item.usage.length > 0 ? item.usage : [];
                        if (usage.length === 0) return;

                        // 安全地获取StartTime
                        const startTime = usage[0]?.StartTime;
                        if (!startTime) return;

                        tempData.push({
                            subcategory: item.subcategory || '其他',
                            [dayjs(startTime).format('YYYY/MM-DD')]:
                                usage.reduce((acc, meter) => {
                                    // 安全地获取并转换Used值
                                    const used = meter && typeof meter.Used !== 'undefined' ? Number(meter.Used) : 0;
                                    return acc + used;
                                }, 0)
                        })
                    })
                }

                // 处理剩余天数的数据
                for (let i = 1; i < data.length; i++) {
                    if (!Array.isArray(data[i])) continue;

                    data[i].forEach(toPushItem => {
                        if (!toPushItem) return;

                        // 确保usage是数组并且有元素
                        const usage = Array.isArray(toPushItem.usage) && toPushItem.usage.length > 0 ? toPushItem.usage : [];
                        if (usage.length === 0) return;

                        // 安全地获取StartTime
                        const startTime = usage[0]?.StartTime;
                        if (!startTime) return;

                        const subcategoryName = toPushItem.subcategory || '其他';
                        let subItem = tempData.find(item => item.subcategory === subcategoryName);

                        if (subItem) {
                            subItem[dayjs(startTime).format('YYYY/MM-DD')] =
                                usage.reduce((acc, meter) => {
                                    // 安全地获取并转换Used值
                                    const used = meter && typeof meter.Used !== 'undefined' ? Number(meter.Used) : 0;
                                    return acc + used;
                                }, 0)
                        }
                    })
                }
                subcategoryData.value = tempData
            } else {
                subcategoryData.value = []
            }
        } catch (error) {
            handleError(error, '获取表格数据失败')
            subcategoryData.value = []
        } finally {
            tableLoading.value = false
        }
    }
})

// 计算表格日期并排序
const dates = computed(() => {
    if (!subcategoryData.value || !subcategoryData.value.length || !subcategoryData.value[0]) return []

    const allDates = Object.keys(subcategoryData.value[0]).filter(key => key !== 'subcategory').filter(key => key !== '0001/01-01')

    return allDates.sort((a, b) => {
        // 安全地处理日期转换
        try {
            const timeA = dayjs(a.replace('/', '-')).valueOf()
            const timeB = dayjs(b.replace('/', '-')).valueOf()
            return timeA - timeB
        } catch (error) {
            console.warn('日期排序错误:', error, a, b);
            return 0; // 保持原有顺序
        }
    })
})

// 格式化日期显示
const formatDate = (date) => {
    if (!date) return '';

    if (date.includes('/')) {
        return date
    }
    return date.replace('-', '/')
}

// 处理表格数据并排序
const tableData = computed(() => {
    if (!subcategoryData.value || !Array.isArray(subcategoryData.value)) {
        return [];
    }

    let data = subcategoryData.value.map(item => {
        if (!item) return null;

        const rowData = {
            subcategory: item.subcategory || '未知',
        }
        let sum = 0

        if (dates.value && Array.isArray(dates.value)) {
            dates.value.forEach(date => {
                if (!date) return;

                const itemValue = item[date];
                sum += itemValue || 0;
                rowData[date] = (itemValue !== undefined && itemValue !== null)
                    ? Number(itemValue).toFixed(2)
                    : '-';
            })
        }
        rowData.sum = sum.toFixed(2)

        return rowData
    }).filter(item => item !== null);
    // 过滤掉所有日期用量都为0的行
    return data.filter(row => {
        return dates.value.some(date => {
            const val = Number(row[date]);
            return !isNaN(val) && val !== 0;
        });
    });
})

// 导出方法
const exportEvent = () => {
    const $table = tableRef.value
    if ($table) {
        $table.openExport({
            filename: "用途用水台账",
            type: "xlsx",
            exportMethod: ({ options }) => {
                return $table.exportData(
                    Object.assign({}, options, {
                        original: false,
                        formatter: true,
                        footer: true,
                        columnFilterMethod: ({ column }) => {
                            return column.property !== "seq"
                        },
                    })
                )
            },
        })
    }
}

</script>
<template>
    <div class="container">
        <div class="left">
            <div class="top">
                <el-card v-loading="pieChartLoading" class="chart-box" style="display: flex; flex-direction: column"
                    body-style="flex: 1;">
                    <template #header>
                        <div class="card-header">
                            <span>用途用水量</span>
                            <CustomDateRadio @update:modelValue="pieChartTime = $event"></CustomDateRadio>
                        </div>
                    </template>
                    <BasePieChart height="210px" :showLegend="false" :data="PieChartData" unit="m³" />
                </el-card>
                <el-card v-loading="trendChartLoading" class="chart-box" style="display: flex; flex-direction: column"
                    body-style="flex: 1;">
                    <template #header>
                        <span>用途用水数据</span>
                        <div class="right-content">
                            <el-select style="width: 35%;" filterable size="small" v-model="selectedSubCategory">
                                <el-option v-for="item in RankingChartData.filter(item => item.name !== '其他')"
                                    :key="item.subcategory" :label="item.name" :value="item.subcategory"></el-option>
                            </el-select>
                            <CustomDateRadio :isFragmentation="true" @update:modelValue="chartTimeRange = $event">
                            </CustomDateRadio>
                        </div>
                    </template>
                    <BaseChart :options="chartOptions" />
                </el-card>
            </div>
            <div class="bottom">
                <el-card v-loading="tableLoading" class="table-box" body-style="flex:1">
                    <template #header>
                        <div class="card-header">
                            <div class="left-content">
                                <span>用途用水台账</span>
                                <CustomDatePicker v-model="tableDataRange" size="small" width="14rem">
                                </CustomDatePicker>
                            </div>
                            <div class="right-content">
                                <el-button type="primary" size="small" @click="exportEvent">
                                    <template #icon>
                                        <SvgIcon icon="download" />
                                    </template>
                                    导出
                                </el-button>
                            </div>
                        </div>
                    </template>
                    <vxe-table v-if="!tableLoading" :export-config="{ type: 'xlsx', useStyle: true }" ref="tableRef"
                        border :data="tableData" height="auto">
                        <vxe-column fixed="left" field="subcategory" title="用途" width="100" align="center" />
                        <template v-for="date in dates" :key="date">
                            <vxe-column :field="date" :title="formatDate(date)" width="120" align="center">
                                <template #default="{ row }">
                                    {{ row[date] }}
                                </template>
                            </vxe-column>
                        </template>
                        <vxe-column title="总计" width="120" align="center">
                            <template #default="{ row }">
                                {{ row.sum }}
                            </template>
                        </vxe-column>
                    </vxe-table>
                </el-card>
            </div>
        </div>
        <div class="right">
            <el-card v-loading="rankingChartLoading" class="sidebar" body-style="flex:1">
                <template #header>
                    <div class="card-header">
                        <span>用途用水排名</span>
                        <CustomDateRadio @update:modelValue="rankingChartTime = $event"></CustomDateRadio>
                    </div>
                </template>
                <BaseRankingChart :horizontal="rankingHorizontal" title="用途用水排名" :data="RankingChartData">
                </BaseRankingChart>
            </el-card>
        </div>
    </div>
</template>
<style scoped>
.container {
    width: 100%;
    height: 100%;
    display: flex;
    gap: 16px;
    box-sizing: border-box;
}

.left {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 16px;
    min-width: 0;
}

.right {
    width: 350px;
    height: 100%;
    flex-shrink: 0;
}

.top {
    display: flex;
    gap: 16px;
    height: 300px;
}

.chart-box {
    flex: 1;
    height: 100%;
    min-width: 0;
}

.bottom {
    flex: 1;
    min-height: 0;
}

.table-box {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.sidebar {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.left-content {
    display: flex;
    align-items: center;
    gap: var(--gap-small);
}

.right-content {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: var(--gap-small);
    flex: 1;
}

@media (max-width: 1400px) {
    .container {
        flex-direction: column;
    }

    .left,
    .right {
        width: 100% !important;
        min-width: 0;
        height: auto;
    }

    .top {
        flex-direction: column;
        height: auto;
    }

    .chart-box {
        min-width: 0;
        height: 220px;
    }

    .sidebar {
        width: 100% !important;
        min-width: 0;
        height: auto;
    }

    .table-box {
        height: 500px;
    }
}
</style>